//
//  ucfSocket.m
//  WXIM
//
//  Created by fusuwei on 14-10-13.
//  Copyright (c) 2014年 naren. All rights reserved.
//

#import "ucfSocket.h"
#import "ucfCallMgr.h"


@interface ucfSocket()<AsyncSocketDelegate>
{
    YY_AsyncSocket *call_sock;
    
    NSInteger continuance;
}
@end

@implementation ucfSocket

- (id)init
{
    self = [super init];
    if (self) {
        [self SocketCreateOpen];
    }
    return self;
}

- (void)dealloc
{
    
}

//创建Socket并连接打开
- (BOOL)SocketCreateOpen
{
    call_sock = [[YY_AsyncSocket alloc] initWithDelegate:self];
    
    continuance=0;
    
    NSLog(@"SocketCreateOpen call_sock= %ld",(long)call_sock);
    
    [call_sock setRunLoopModes:[NSArray arrayWithObject:NSRunLoopCommonModes]];
    
    if (![self SocketOpen:@"192.168.20.96" port:5678])
    {
        //            NSMutableString *sendString=[NSMutableString stringWithCapacity:1000];
        //            [sendString appendString:@"hello world!"];
        //            NSData *cmdData = [sendString dataUsingEncoding:NSUTF8StringEncoding];
        //
        //            [_sock writeData:cmdData withTimeout:-1 tag:0];
    }
    return YES;
}

//发送数据
-(void)writeDataOnOtherThread:(NSData *)cmdData
{
    NSLog(@"writeDataOnOtherThread len= %ld",(long)[cmdData length]);
    //NSData *cmdData = [string dataUsingEncoding:NSUTF8StringEncoding];
    
    [call_sock writeData:cmdData withTimeout:-1 tag:0];
}

//打开Socket
- (NSInteger)SocketOpen:(NSString*)addr port:(NSInteger)port
{
    if (![call_sock isConnected])
    {
        [call_sock connectToHost:addr onPort:port withTimeout:-1 error:nil];
        
        NSLog(@"SocketOpen connect to Host:%@ Port:%ld",addr,(long)port);
    }
    return 0;
}

//写数据发送
- (NSInteger)SocketWrite:(NSString*)cmd level:(NSInteger)level
{
    if ([call_sock isConnected])
    {
        //处理发送数据，加入队列等待发送
    }
    else
    {
        NSLog(@"Offline!");
    }
    return 0;
}

//关闭Socket
- (NSInteger)SocketClose
{
    if ([call_sock isConnected])
    {
        [call_sock disconnectAfterReadingAndWriting];
    }
    return 0;
}


#pragma mark -
#pragma mark Delegate

- (void)onSocket:(YY_AsyncSocket *)sock willDisconnectWithError:(NSError *)err
{
    NSLog(@"willDisconnectWithError:%@",err);
    [self.delegate onSocket:sock willDisconnectWithError:err];
}

- (void)onSocketDidDisconnect:(YY_AsyncSocket *)sock
{
    NSLog(@"onSocketDidDisconnect");
    [self.delegate onSocketDidDisconnect:sock];
}

- (void)onSocket:(YY_AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port
{
    NSLog(@"didConnectToHost");
    
    //这是异步返回的连接成功，
    [self performSelectorOnMainThread:@selector(onCocketConnectToHost:) withObject:@"success" waitUntilDone:[NSThread isMainThread]];
}

- (void)onCocketConnectToHost:(NSString*)state
{
    // NSLog(@"recvData: %@",rcvdata);
    
    [[ucfCallMgr sharedInstance] onCocketConnectToHost:@"success"];
    
}

- (void)onSocket:(YY_AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
    //NSString *rcvdata = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    
    NSLog(@"收到的数据len= %ld",(long)[data length]);
//    if(rcvdata)
//    {
//        //处理受到的数据
//        NSLog(@"收到的数据:%@",rcvdata);
//        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"收到数据" message:rcvdata delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
//        [alert show];
//    }
//    else
//    {
//        NSLog(@"Error converting received data into UTF-8 String");
//    }
    
//    NSString *message= @"连接成功";
//    NSData *cmdData = [message dataUsingEncoding:NSUTF8StringEncoding];
//    [sock writeData:cmdData withTimeout:-1 tag:0];
    
    [self performSelectorOnMainThread:@selector(recvData:) withObject:data waitUntilDone:[NSThread isMainThread]];
    
    
    [sock readDataWithTimeout:-1 tag:0];
}

- (void)recvData:(NSData*)rcvdata
{
   // NSLog(@"recvData: %@",rcvdata);
    
    [[ucfCallMgr sharedInstance] btnPlay:rcvdata];
    
}

-(void)onSocket:(YY_AsyncSocket *)sock didWriteDataWithTag:(long)tag
{
    NSLog(@"didWriteDataWithTag:%ld",tag);
    [sock readDataWithTimeout:-1 tag:0];
    
    [self.delegate onSocket:sock didWriteDataWithTag:tag];
}

@end
